package com.ddfeiyu.common;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SocketChannelUtil {


    // traceId
    private static Map<String/*traceId*/, Channel> traceChannel = new ConcurrentHashMap<>();
    private static Map<String/*channelId*/, String/*traceId*/> traceChannelId = new ConcurrentHashMap<>();
    // traceId群组
    private static Map<String, ChannelGroup> channelGroupMap = new ConcurrentHashMap<>();

    /**
     * 绑定traceId和通道
     * @param traceId
     * @param channel
     */
    public static void addChannel(String traceId, Channel channel) {
        traceChannel.put(traceId, channel);
        traceChannelId.put(channel.id().toString(), traceId);
    }


    public static Channel getChannel(String traceId) {
        return traceChannel.get(traceId);
    }

    public static void removeChannel(String channelId){
        String userId = traceChannelId.get(channelId);
        if (null == userId) {
            return;
        }
        traceChannel.remove(userId);
    }

    public static void removeChannelGroupByChannel(Channel channel){
        for (ChannelGroup next : channelGroupMap.values()) {
            next.remove(channel);
        }
    }

    /**
     * 移除
     * @param traceId
     */
    public static void removeUserChannelByUserId(String traceId){
        traceChannel.remove(traceId);
    }

}
